<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表名称" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入湖名称" prop="lakeName">
        <el-input
          v-model="queryParams.lakeName"
          placeholder="请输入入湖名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="全量增量" prop="increaseAll">
        <el-select v-model="queryParams.increaseAll" placeholder="入湖增全量">
            <el-option
              key="0"
              label="全量"
              value="0"
            />
            <el-option
              key="1"
              label="增量"
              value="1"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="执行周期" prop="cycle">
        <el-select v-model="queryParams.cycle" placeholder="入湖执行周期">
            <el-option
              key="D"
              label="日"
              value="D"
            />
            <el-option
              key="M"
              label="月"
              value="M"
            />
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['boc:lakeTable:edit']"
          v-show="false"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['boc:lakeTable:remove']"
        >删除</el-button> 
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="openImportTable"
          v-hasPermi="['boc:lakeTable:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['boc:lakeTable:import']"
        >批量导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['boc:lakeTable:export']"
          v-show="false"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="batchDownLoadLakeCode"
          v-hasPermi="['boc:lakeTable:export']"
        >批量导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="lakeTableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="tableId" />
      <el-table-column label="表名称" align="center" prop="tableName" />
      <el-table-column label="表描述" align="center" prop="tableComment" />
      <el-table-column label="入湖名称" align="center" prop="lakeName" width="200px"/>
      <el-table-column label="0:全量1:增量" align="center" prop="increaseAll" />
      <el-table-column label="D:日M:月" align="center" prop="cycle" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="入湖信息" align="center" class-name="small-padding fixed-width" width="180px">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['boc:lakeTable:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['boc:lakeTable:remove']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="入湖字段" align="center" class-name="small-padding fixed-width" width="180px">
        <template #default="scope">
          <el-button link type="primary" icon="Refresh" @click="handleRefresh(scope.row)" v-hasPermi="['boc:lakeTable:edit']">同步</el-button>
          <el-button link type="primary" icon="CircleCheck" @click="handleEdit(scope.row)" v-hasPermi="['boc:lakeTable:edit']">编辑</el-button>
        </template>
      </el-table-column>
      <el-table-column label="生成入湖代码" align="center" class-name="small-padding fixed-width" width="250px">
        <template #default="scope">
          <el-button  type="primary" @click="handlePreview(scope.row)" v-hasPermi="['boc:lakeTable:edit']">预览</el-button>
          <el-button  type="success" @click="downLoadLakeCode(scope.row)" v-hasPermi="['boc:lakeTable:edit']">生成代码</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入湖生成业务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="lakeTableRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="表名称" prop="tableName">
          <el-input v-model="form.tableName" placeholder="请输入表名称" readonly/>
        </el-form-item>
        <el-form-item label="表描述" prop="tableComment">
          <el-input v-model="form.tableComment" type="textarea" placeholder="请输入内容" readonly/>
        </el-form-item>
        <el-form-item label="入湖名称" prop="lakeName">
          <el-input v-model="form.lakeName" placeholder="请输入入湖名称" />
        </el-form-item>
        <el-form-item label="全量增量" prop="increaseAll">
          <el-select v-model="form.increaseAll" placeholder="请输入0:全量1:增量" style="width: 380px">
            <el-option
              key="0"
              label="全量"
              value="0"
            />
            <el-option
              key="1"
              label="增量"
              value="1"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="执行周期" prop="cycle">
          <el-select v-model="form.cycle" placeholder="请输入D:日M:月Y:年" style="width: 380px">
            <el-option
              key="D"
              label="日"
              value="D"
            />
            <el-option
              key="M"
              label="月"
              value="M"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览界面 -->
    <el-dialog :title="preview.title" v-model="preview.open" width="80%"  top="5vh" append-to-body class="scrollbar">
      <el-tabs v-model="preview.activeName">
        <el-tab-pane label="代码" name="first">
          <el-link :underline="false" icon="DocumentCopy" v-copyText="preview.data" v-copyText:callback="copyTextSuccess" style="float:right">&nbsp;复制</el-link>
          <pre style="height:550px" class="custom-scroll">{{ preview.data }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
         <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
         >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <div class="el-upload__tip">
                     <el-checkbox v-model="upload.updateSupport" />如已经存在，是否删除后再上传
                  </div>
                  <span>仅允许导入xls、xlsx格式文件。</span>
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
               </div>
            </template>
         </el-upload>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFileForm">确 定</el-button>
               <el-button @click="upload.open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>

    <import-table ref="importRef" @ok="handleQuery" />
  </div>
</template>

<script setup name="LakeTable">
import { getToken } from "@/utils/auth";
import { listLakeTable, getLakeTable, delLakeTable, addLakeTable, updateLakeTable, synchGbaseDb, previewLakeTable } from "@/api/boc/lakeTable";
import importTable from "./importTable";
const router = useRouter();

const { proxy } = getCurrentInstance();

const lakeTableList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const tableNames = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const multipleSelection = ref([]);


const columnTitle = ref("");
const columnOpen = ref(false);

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/boc/lakeTable/importBocLakeData"
});


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tableName: null,
    tableComment: null,
    lakeName: null,
    increaseAll: null,
    cycle: null,
  },
  preview: {
    open: false,
    title: "代码预览",
    data: {},
    activeName: "first"
  },
  rules: {
    lakeName: [
      { required: true, message: "入湖名称不能为空", trigger: "blur" }
    ],
    increaseAll: [
      { required: true, message: "0:全量1:增量不能为空", trigger: "blur" }
    ],
    cycle: [
      { required: true, message: "D:日M:月Y:年不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, preview, form, rules } = toRefs(data);

/** 查询入湖生成业务列表 */
function getList() {
  loading.value = true;
  listLakeTable(queryParams.value).then(response => {
    lakeTableList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    tableId: null,
    tableName: null,
    tableComment: null,
    lakeName: null,
    increaseAll: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("lakeTableRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.tableId);
  tableNames.value = selection.map(item => item.tableName);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  multipleSelection.value = selection;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加入湖生成业务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _tableId = row.tableId || ids.value
  getLakeTable(_tableId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改入湖生成业务";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["lakeTableRef"].validate(valid => {
    if (valid) {
      if (form.value.tableId != null) {
        updateLakeTable(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLakeTable(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _tableIds = row.tableId || ids.value;
  proxy.$modal.confirm('是否确认删除入湖生成业务编号为"' + _tableIds + '"的数据项？').then(function() {
    return delLakeTable(_tableIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('boc/lakeTable/export', {
    ...queryParams.value
  }, `lakeTable_${new Date().getTime()}.xlsx`)
}
/** 打开导入表弹窗 */
function openImportTable() {
  proxy.$refs["importRef"].show();
}

/** 生成入湖代码 */
function downLoadLakeCode(row){
  const tableName = row.tableName;
  const tableId = row.tableId;
  const cycle = row.cycle;
  if (tableName == "") {
    proxy.$modal.msgError("请选择要生成的数据");
    return;
  }
  if(cycle ==""){
    proxy.$modal.msgError("入湖信息未填全");
    return;
  }
  proxy.$download.zip("/boc/lakeTable/downLoadLakeCode?tableId=" + tableId, `${tableName}_lake.sh`);
}

function batchDownLoadLakeCode(row){
  const tableIds = row.tableId || ids.value;
  if (tableIds == "") {
    proxy.$modal.msgError("请选择要生成的数据");
    return;
  }
  let flat = 0;
  multipleSelection.value.forEach(row =>{
    if(row.cycle == ""){
      flat =1;
    }
  });
  if(flat == 1){
    proxy.$modal.msgError("入湖信息未填全");
    return;
  }
    proxy.$download.zip("/boc/lakeTable/batchDownLoadLakeCode?tableIds=" + tableIds, `lake_${new Date().getTime()}.zip`);
}

function handleRefresh(row){
  const tableName = row.tableName;
  proxy.$modal.confirm('确认要强制同步"' + tableName + '"表结构吗？').then(function () {
    return synchGbaseDb(tableName);
  }).then(() => {
    proxy.$modal.msgSuccess("同步成功");
  }).catch(() => {});
}

/** 任务日志列表查询 */
function handleEdit(row) {
  const tableId = row.tableId;
  router.push('/boc/lakeTableColumn-edit/index/' + tableId)
}

/** 预览按钮 */
function handlePreview(row) {
  const tableName = row.tableName;
  const cycle = row.cycle;
  if (tableName == "") {
    proxy.$modal.msgError("请选择要生成的数据");
    return;
  }
  if(cycle ==""){
    proxy.$modal.msgError("入湖信息未填全");
    return;
  }
  previewLakeTable(row.tableId).then(response => {
    preview.value.data = response.msg;
    preview.value.open = true;
    preview.value.activeName = "first";
  });
}

/** 复制代码成功 */
function copyTextSuccess() {
  proxy.$modal.msgSuccess("复制成功");
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
};
/** 下载模板操作 */
function importTemplate() {
  proxy.download("boc/lakeTable/importBocLakeTemplate", {
  }, `lakeTable_template_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

getList();
</script>

<style lang='scss' scoped>

.custom-scroll {
  overflow-y:auto;
  max-height:550px
}
</style>

